﻿using UnityEngine;
using System.Collections;
using System;
using Game.Scripts.Managers;
using FrenzyIsland.UI;

[RequireComponent(typeof(Building))]
public class BuildingMouseAction : MonoBehaviour {

    private float rotation = 2;
    private float radius = 2;
    private float height = -0.3f;
    private GameObject selectionObjectInstance;

    /// <summary>
    /// Esegue l'azione specificata per ogni tipo di oggetto
    /// Cambia il colore
    /// </summary>
    public void OnMouseDown() {
        //abilito l'evento solo se il click non cade attraverso un collider dell'interfaccia
        if (UICamera.lastHit.collider == null) {
            Building building = this.GetComponent<Building>();
            if (building != null) {
                GuiManager guiManager = UIRoot.list[0].GetComponent<GuiManager>();
                GameObject widget = guiManager.openWidget(BuildingManager.instance.UIMenuSelectedBuilding);
                widget.GetComponent<SelectedBuildingModel>().building = building;
                this.changeColor(Color.red);
            }
        }
    }
    
    public void OnMouseEnter(){
        if (this.selectionObjectInstance == null) {
            if (BuildingManager.instance.selectorObject != null) {
                GameObject prefabSelector = BuildingManager.instance.selectorObject;
                Building building = this.GetComponent<Building>();
                if (building != null) {
                    this.selectionObjectInstance = Instantiate(prefabSelector) as GameObject;
                    this.selectionObjectInstance.name = "SelectorObject";
                    this.selectionObjectInstance.transform.parent = building.transform;
                    this.selectionObjectInstance.transform.localScale = new Vector3(this.radius, 0.001f, this.radius);
                    this.selectionObjectInstance.transform.localPosition = new Vector3(0, this.height, 0);
                }
            }
        }
    }


    public void OnMouseExit(){
        if (this.selectionObjectInstance) {
            Destroy(this.selectionObjectInstance);
            this.selectionObjectInstance = null;
        }
    }


    private void changeColor(Color color){
        if (this.selectionObjectInstance) {
            MeshRenderer rend = selectionObjectInstance.GetComponent<MeshRenderer>();
            rend.material.color = color;
        }
    }
}
